/**
 * Created by zhangyu on 2017/3/24.
 */
require(['zTreeCheckbox', 'grid', 'layout'], function () {
    var userInfo = commonFun.execParentMethod("getUserInfo");
    var left = $("#left"),//fieldsTab,
        funcList = $("#funcList"),
        fieldsTab = $("#fieldsTab"),
        $sysRoleTree = $("#sysRoleTree"),
        funcId;

    fieldsTab.grid({
        url: "/sysAuthorityFunc/getCurrentFieldData.htm",
        showPager: false,
        // width: $(window).width() - 600,
        // height: $(window).height() - 110,
        colModel: [{name: "id", key: true, label: 'id', hidden: true},
            {name: "tableDsc", label: '表名称', index: "tableDsc", width: "110"},
            {name: "fieldDsc", label: '字段名称', index: "fieldDsc"},
            {name: "fieldAlias", label: '字段别名', index: "fieldAlias", editable: true}],
        gridComplete: function () {
            var fieldIds = fieldsTab.grid("getDataIDs");
            var fieldId;
            for (var i in fieldIds) {
                fieldId = fieldIds[i];
                var fieldData = fieldsTab.grid("getRowData", fieldId);
                var fieldAliasHtml = "<input type='text' fieldId='" + fieldId
                    + "' value='" + fieldData.fieldAlias
                    + "' class='u-input dataRow' style='width:140px;'/>";
                fieldsTab.grid('setRowData', fieldId, {
                    fieldAlias: fieldAliasHtml
                });
            }
            // 选中其已分配的资源权限数据
            if ($("#roleId").val() && funcId) {
                $.ajaxExt({
                    // async:true,
                    url: "/sysAuthorityFunc/getCheckedFieldData.htm",
                    data: {
                        "roleId": $("#roleId").val(),
                        "funcId": funcId
                    }
                }).done(function (data) {
                    for (var i in data) {
                        fieldsTab.jqGrid("setSelection", data[i].id);
                    }
                });
            }
        }
    });

    initSysRoleTree();

    /**
     * 获得节点数据，并且生成左侧的树
     */
    function initSysRoleTree() {
        $.ajaxExt({
            async: true,
            url: "/sysRole/getSysRoleByName.htm"
        }).done(function (data) {
            if (!data) {
                data = [];
            }
            // 树的参数配置
            var setting = {
                data: {
                    key: {
                        name: "name"
                    },
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "parentRoleId",
                        rootPId: 0
                    }
                },
                view: {
                    showIcon: true
                },
                callback: {
                    onClick: sysRoleTreeClick
                }
            };
            // 生成树
            sysRoleTreeObj = $sysRoleTree.createTree(setting, data, {search: $('#search-text')});
            sysRoleTreeObj.setting.view.expandSpeed = "";
            sysRoleTreeObj.expandAll(true);
            sysRoleTreeObj.setting.view.expandSpeed = "fast";
            getAndSelectRootNode();// 选中根节点，触发事件
        });
    }

    function getAndSelectRootNode() {
        var node = sysRoleTreeObj.getNodesByFilter(function (node) {
            return node.level == 0;
        }, true);
        sysRoleTreeObj.selectNode(node, false);
        sysRoleTreeClick(null, node.id, node, true);
    }

    function sysRoleTreeClick(event, treeId, treeNode, clickFlag) {
        $("#roleId").val(treeNode.id);
        $.ajaxExt({
            url:"/sysAuthorityFunc/getAuthFuncList.htm",
            data: {
                "roleId": treeNode.id,
                "roleType" : treeNode.roleType
            }
        }).done(function(data){
            funcList.empty();
            if(data && data.length > 0){
                $.each(data, function (index, item) {
                    funcList.append("<li class='bbh' funcId='" + item.id + "'><a>" + item.name + "</a></li>");
                });
            }
        });
    }


    funcList.on('click', 'li', function () {
        if ($("#roleId").val()) {
            if (this.className.indexOf('active') == -1) {
                $(this).addActiveClass();
                funcId = $(this).attr("funcId");
                initRight();
            }
        } else {
            $.messager.alert("提示", "请选择左侧树，进行查询操作。", "info");
        }
    });

    function initRight(){
        fieldsTab.grid('setGridParam', {
            datatype: "json",
            postData: {
                roleId: $("#roleId").val(),
                "funcId": funcId
            }
        }).trigger("reloadGrid");
    }


    $("#update").click(function(){
        var fieldIds = [], fieldAliases = [];
        if (funcId) {
            fieldIds = fieldsTab.grid("getGridParam", "selarrrow"); // 获取选中的字段权限
            $('.dataRow').each(function (i) {
                for (var i in fieldIds) {
                    if ($(this).attr("fieldId") === fieldIds[i]) {
                        fieldAliases.push($(this).val());
                    }
                }
            });
        }

        $.ajaxExt({
            url : "/sysAuthorityFunc/saveFieldAuthority.htm",
            data : {
                "fieldIds": fieldIds,
                "fieldAliases": fieldAliases,
                "roleId": $("#roleId").val(),
                "funcId": funcId
            }
        }).done(function(data){
            initRight();
        });
    });

    function resize() {
        var winHeight = $(window).height();
        //设置功能权限树高和宽
        $('#tree').css({
            height: winHeight - 111
        });
        //设置角色树高度
        $sysRoleTree.height(winHeight - 55);
        $("#left,#right").height(winHeight);
        fieldsTab.grid('setGridHeight', winHeight - 200);
        fieldsTab.grid('setGridWidth', $(window).width() - 500);
    }

    $(window).on('resize', resize).trigger('resize');
    $('body').layout();

});